<template>
  <div>
    <el-card style="margin-bottom: 10px">
      <div
        style="
          display: flex;
          flex-direction: row;
          justify-content: space-between;
        "
      >
        <div>
          <div class="verticalBar"></div>
          <span style="color: #1074fd">拓客</span>
        </div>
        <div>
          <span style="color: #999999; font-size: 12px">数据每日00:00更新</span>
        </div>
      </div>
    </el-card>

    <div class="middle_box">
      <div id="mapBox" style="width: 1160px; height: 900px"></div>
      <div class="right_box">
        <!-- <div>
          <el-select
            class="right_box_select"
            v-model="value"
            placeholder="请选择行业"
          >
            <el-option
              v-for="(item, index) in type"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <el-select
            class="right_box_select"
            v-model="value"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-select
            class="right_box_select"
            v-model="value"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div> -->
        <div>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <!-- <el-tab-pane label="全图拓客" name="first"></el-tab-pane> -->
            <el-tab-pane label="行业拓客" name="second"></el-tab-pane>
            <!-- <el-tab-pane label="距离拓客" name="third"></el-tab-pane> -->
          </el-tabs>
        </div>
        <el-input
          v-model="input"
          id="input"
          placeholder="搜索地区"
          style="width: 500px"
          @keyup.enter.native="huichesearch"
        ></el-input>
        <div class="bottom_box">
          <el-input
            v-model="inputCI"
            id="input"
            placeholder="输入关键字"
            style="width: 210px"
            @keyup.enter.native="huichesearch"
          ></el-input>
          <el-select
            class="right_box_select"
            v-model="value"
            placeholder="请选择行业"
          >
            <el-option
              v-for="(item, index) in type"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <!-- <el-button type="primary" id="places">搜索地区</el-button> -->
          <el-button type="primary" id="search">搜索商家</el-button>
          <!-- <el-button type="primary" id="clear">清除地区</el-button> -->
          <el-button type="primary" @click="clearMarker">清除</el-button>
        </div>
        <div class="bottom_box_right">
          <el-checkbox style="margin-left: 10px" v-model="checked"
            >全选</el-checkbox
          >
          <div @click="uploadDataTxt">
            <button class="upload_box">
              <i class="el-icon-upload2" style="color: #fd9e10"></i>
              <div>导出txt文件</div>
            </button>
          </div>
          <div @click="uploadDataVcf">
            <button class="upload_box">
              <i class="el-icon-upload2" style="color: #fd9e10"></i>
              <div>导出vcf文件</div>
            </button>
          </div>
        </div>
        <div class="detail">
          <div
            class="info_boss"
            v-for="(item, index) in placeDetail"
            :key="index"
          >
            <div class="info_box">
              <el-checkbox v-model="checked" class="name_el">{{
                item.name
              }}</el-checkbox>
              <div class="phone_el">
                ({{ item.international_phone_number }})
              </div>
            </div>
            <div class="address">地址：{{ item.formatted_address }}</div>
          </div>
        </div>
        <div class="fenye">
          <el-pagination
            small
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, prev, pager, next"
            :page-size="queryLine.pageSize"
            :total="placeDetail.length"
          >
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import { gmapApi } from "vue2-google-maps";
// import { MarkerClusterer } from "@googlemaps/markerclusterer";
import { saveAs } from "file-saver";
let responseDiv;
let response;
// let getNextPage;

export default {
  data() {
    return {
      value: "",
      activeName: "second",
      input: "",
      inputCI: "",
      checked: false,
      queryLine: {
        pageNum: 1,
        pageSize: 500,
      },
      inputText: null,
      map: null,
      marker: null,
      marker_clear: null,
      geocoder: null,
      // 地图中心经纬度
      center: {
        lat: 40.75,
        lng: -73.97,
      },
      // 鼠标点击位置
      clickLocation: null,
      zoom: 13,
      $inputText: this.inputText,
      // 初始化信息窗口
      infoWindow: null,
      service: null,
      details: [],
      placeId: [],
      locations: [],
      placeDetail: [],
      type: [
				{
					value: "accounting",
					label: '会计'
				},
				{
					value: "airport",
					label: '机场'
				},
				{
					value: "amusement_park",
					label: '游乐园'
				},
				{
					value: "aquarium",
					label: '水族馆'
				},
				{
					value: "art_gallery",
					label: '艺术画廊'
				},
				{
					value: "atm",
					label: '自动提款机'
				},
				{
					value: "bakery",
					label: '面包房'
				},
				{
					value: "bank",
					label: '银行'
				},
				{
					value: "bar",
					label: '酒吧'
				},
				{
					value: "beauty_salon",
					label: '美容院'
				},
				{
					value: "bicycle_store",
					label: '自行车店'
				},
				{
					value: "book_store",
					label: '书店'
				},
				{
					value: "bowling_alley",
					label: '胡同'
				},
				{
					value: "bus_station",
					label: '公交车站'
				},
				{
					value: "cafe",
					label: '咖啡馆'
				},
				{
					value: "campground",
					label: '露营地'
				},
				{
					value: "car_dealer",
					label: '汽车经销商'
				},
				{
					value: "car_rental",
					label: '租车'
				},
				{
					value: "car_repair",
					label: '汽车修理'
				},
				{
					value: "car_wash",
					label: '洗车'
				},
				{
					value: "casino",
					label: '赌场'
				},
				{
					value: "cemetery",
					label: '墓地'
				},
				{
					value: "church",
					label: '教室'
				},
				{
					value: "city_hall",
					label: '市政厅'
				},
				{
					value: "clothing_store",
					label: '服装店'
				},
				{
					value: "convenience_store",
					label: '便利店'
				},
				{
					value: "courthouse",
					label: '法院'
				},
				{
					value: "dentist",
					label: '牙医'
				},
				{
					value: "department_store",
					label: '百货公司'
				},
				{
					value: "doctor",
					label: '医生'
				},
				{
					value: "drugstore",
					label: '药店'
				},
				{
					value: "electrician",
					label: '电工'
				},
				{
					value: "electronics_store",
					label: '电子商店'
				},
				{
					value: "embassy",
					label: '大使馆'
				},
				{
					value: "fire_station",
					label: '消防局'
				},
				{
					value: "florist",
					label: '花商'
				},
				{
					value: "funeral_home",
					label: '殡仪馆'
				},
				{
					value: "furniture_store",
					label: '家具店'
				},
				{
					value: "gas_station",
					label: '加油站'
				},
				{
					value: "gym",
					label: '健身房'
				},
				{
					value: "hair_care",
					label: '护发'
				},
				{
					value: "hardware_store",
					label: '五金店'
				},
				{
					value: "hindu_temple",
					label: '印度教寺庙'
				},
				{
					value: "home_goods_store",
					label: '家居用品店'
				},
				{
					value: "hospital",
					label: '医院'
				},
				{
					value: "insurance_agency",
					label: '保险公司'
				},
				{
					value: "jewelry_store",
					label: '珠宝店'
				},
				{
					value: "laundry",
					label: '洗衣房'
				},
				{
					value: "lawyer",
					label: '律师'
				},
				{
					value: "library",
					label: '图书馆'
				},
				{
					value: "light_rail_station",
					label: '轻轨站'
				},
				{
					value: "liquor_store",
					label: '酒类商店'
				},
				{
					value: "local_government_office",
					label: '当地政府办公室'
				},
				{
					value: "locksmith",
					label: '锁匠'
				},
				{
					value: "lodging",
					label: '住宿'
				},
				{
					value: "meal_delivery",
					label: '送饭'
				},
				{
					value: "meal_takeaway",
					label: '外卖'
				},
				{
					value: "mosque",
					label: '清真寺'
				},
				{
					value: "movie_rental",
					label: '电影出租'
				},
				{
					value: "movie_theater",
					label: '电影院'
				},
				{
					value: "moving_company",
					label: '搬家公司'
				},
				{
					value: "museum",
					label: '博物馆'
				},
				{
					value: "night_club",
					label: '夜总会'
				},
				{
					value: "painter",
					label: '画家'
				},
				{
					value: "park",
					label: '公园'
				},
				{
					value: "parking",
					label: '停车场'
				},
				{
					value: "pet_store",
					label: '宠物店'
				},
				{
					value: "pharmacy",
					label: '药房'
				},
				{
					value: "physiotherapist",
					label: '物理治疗师'
				},
				{
					value: "plumber",
					label: '水管工'
				},
				{
					value: "police",
					label: '警察'
				},
				{
					value: "post_office",
					label: '邮局'
				},
				{
					value: "primary_school",
					label: '小学'
				},
				{
					value: "real_estate_agency",
					label: '房地产中介'
				},
				{
					value: "restaurant",
					label: '餐厅'
				},
				{
					value: "roofing_contractor",
					label: '屋顶承包商'
				},
				{
					value: "rv_park",
					label: '房车公园'
				},
				{
					value: "school",
					label: '学校'
				},
				{
					value: "secondary_school",
					label: '中学'
				},
				{
					value: "shoe_store",
					label: '鞋店'
				},
				{
					value: "shopping_mall",
					label: '购物中心'
				},
				{
					value: "spa",
					label: '水疗'
				},
				{
					value: "stadium",
					label: '体育场'
				},
				{
					value: "storage",
					label: '存储'
				},
				{
					value: "store",
					label: '商店'
				},
				{
					value: "subway_station",
					label: '地铁站'
				},
				{
					value: "supermarket",
					label: '超市'
				},
				{
					value: "synagogue",
					label: '犹太教堂'
				},
				{
					value: "taxi_stand",
					label: '出租车站'
				},
				{
					value: "tourist_attraction",
					label: '旅游景点'
				},
				{
					value: "train_station",
					label: '火车站'
				},
				{
					value: "transit_station",
					label: '中转站'
				},
				{
					value: "travel_agency",
					label: '旅行社'
				},
				{
					value: "university",
					label: '大学'
				},
				{
					value: "veterinary_care",
					label: '兽医护理'
				},
				{
					value: "zoo",
					label: '动物园'
				},
      ],
      // type: [
      //   "accounting",
      //   "airport",
      //   "amusement_park",
      //   "aquarium",
      //   "art_gallery",
      //   "atm",
      //   "bakery",
      //   "bank",
      //   "bar",
      //   "beauty_salon",
      //   "bicycle_store",
      //   "book_store",
      //   "bowling_alley",
      //   "bus_station",
      //   "cafe",
      //   "campground",
      //   "car_dealer",
      //   "car_rental",
      //   "car_repair",
      //   "car_wash",
      //   "casino",
      //   "cemetery",
      //   "church",
      //   "city_hall",
      //   "clothing_store",
      //   "convenience_store",
      //   "courthouse",
      //   "dentist",
      //   "department_store",
      //   "doctor",
      //   "drugstore",
      //   "electrician",
      //   "electronics_store",
      //   "embassy",
      //   "fire_station",
      //   "florist",
      //   "funeral_home",
      //   "furniture_store",
      //   "gas_station",
      //   "gym",
      //   "hair_care",
      //   "hardware_store",
      //   "hindu_temple",
      //   "home_goods_store",
      //   "hospital",
      //   "insurance_agency",
      //   "jewelry_store",
      //   "laundry",
      //   "lawyer",
      //   "library",
      //   "light_rail_station",
      //   "liquor_store",
      //   "local_government_office",
      //   "locksmith",
      //   "lodging",
      //   "meal_delivery",
      //   "meal_takeaway",
      //   "mosque",
      //   "movie_rental",
      //   "movie_theater",
      //   "moving_company",
      //   "museum",
      //   "night_club",
      //   "painter",
      //   "park",
      //   "parking",
      //   "pet_store",
      //   "pharmacy",
      //   "physiotherapist",
      //   "plumber",
      //   "police",
      //   "post_office",
      //   "primary_school",
      //   "real_estate_agency",
      //   "restaurant",
      //   "roofing_contractor",
      //   "rv_park",
      //   "school",
      //   "secondary_school",
      //   "shoe_store",
      //   "shopping_mall",
      //   "spa",
      //   "stadium",
      //   "storage",
      //   "store",
      //   "subway_station",
      //   "supermarket",
      //   "synagogue",
      //   "taxi_stand",
      //   "tourist_attraction",
      //   "train_station",
      //   "transit_station",
      //   "travel_agency",
      //   "university",
      //   "veterinary_care",
      //   "zoo",
      // ],
      query: "book",
      vcord: null,
      file: null,
    };
  },
  computed: {
    // google: gmapApi,
  },
  mounted() {
    this.initMap();
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
      console.log(this.google);
    },
    initMap() {
      this.map = new google.maps.Map(document.getElementById("mapBox"), {
        zoom: 12,
        center: this.center,
        mapTypeControl: false,
        // panControl: false,
        // zoomControl: false,
        // streetViewControl: false,
      });

      // 创建初始信息窗口
      // this.infoWindow = new google.maps.InfoWindow({
      // content: "请点击地区获取当前经经纬度",
      //   position: this.center,
      // });
      // this.infoWindow.open(this.map);

      // 点击地图获取点击位置经纬度
      this.map.addListener("click", (mapsMouseEvent) => {
        // 删除初始信息窗口
        // this.infoWindow.close();
        // 创建新的信息窗口
        // this.infoWindow = new google.maps.InfoWindow({
        //   position: mapsMouseEvent.latLng,
        // });
        // this.infoWindow.setContent(
        //   JSON.stringify(mapsMouseEvent.latLng.toJSON(), null, 2)
        // );
        this.clickLocation = mapsMouseEvent.latLng.toJSON();
        //重新定位中心=位置
        this.center = mapsMouseEvent.latLng.toJSON();
        this.placeId = [];
        this.locations = [];
        // console.log(this.center);
        console.log(this.clickLocation);
        // this.infoWindow.open(this.map);
      });

      this.geocoder = new google.maps.Geocoder();

      // const inputText = document.createElement("input");
      this.inputText = document.getElementById("input");

      // inputText.type = "text";
      // inputText.placeholder = "Enter a location";

      // const submitButton = document.createElement("input");
      const submitButton = document.getElementById("search");
      const submitButtonPlaces = document.getElementById("places");

      // submitButton.type = "button";
      // submitButton.value = "Geocode";
      // submitButton.classList.add("button", "button-primary");

      // const clearButton = document.createElement("clear");
      // const clearButton = document.getElementById("clear");

      // clearButton.type = "button";
      // clearButton.value = "Clear";
      // clearButton.classList.add("button", "button-secondary");

      response = document.createElement("pre");
      response.id = "response";
      response.innerText = "";
      responseDiv = document.createElement("div");
      responseDiv.id = "response-container";
      responseDiv.appendChild(response);

      // 在地图里面添加控件
      // map.controls[google.maps.ControlPosition.TOP_LEFT].push(inputText);
      // map.controls[google.maps.ControlPosition.TOP_LEFT].push(submitButton);
      // map.controls[google.maps.ControlPosition.TOP_LEFT].push(clearButton);
      // map.controls[google.maps.ControlPosition.LEFT_TOP].push(responseDiv);
      this.marker = new google.maps.Marker({
        map: this.map,
      });
      this.marker_clear = new google.maps.Marker({
        map: this.map,
      });
      // this.map.addListener("click", (e) => {
      //   console.log(e);
      //   this.geocode({ location: e.latLng });
      // });

      submitButton.addEventListener("click", () => this.nearSearch());

      // function search() {
      //   submitButtonPlaces.addEventListener("click", () =>
      //     this.geocode({ address: this.inputText.value })
      //   );
      // }
      // clearButton.addEventListener("click", () => {
      //   this.clear();
      // });
      this.clear();
    },
    clear() {
      this.marker_clear.setMap(null);
      // responseDiv.style.display = "none";
    },

    //回车搜索
    huichesearch(e) {
      let keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        this.geocode({ address: this.inputText.value });
      }
    },

    // 搜索地区
    geocode(request) {
      this.clear();
      this.geocoder
        .geocode(request)
        .then((result) => {
          const { results } = result;
          this.map.setCenter(results[0].geometry.location, 2);
          this.marker_clear.setPosition(results[0].geometry.location);
          this.marker_clear.setMap(this.map);
          responseDiv.style.display = "block";
          response.innerText = JSON.stringify(result, null, 2);
          return results;
        })
        .catch((e) => {
          alert("Geocode was not successful for the following reason: " + e);
        });
    },

    // 范围搜索
    nearSearch() {
      // this.clearMarker();
      var request = {
        // location: this.center,
        radius: "50000",
        bounds: this.map.getBounds(),
        types: [this.value],
        query: this.inputCI,
      };
      this.service = new google.maps.places.PlacesService(this.map);
      // this.service.nearbySearch(request, this.callbackNear);
      this.service.textSearch(request, this.callbackNear);
    },

    callbackNear(results, status, pagination) {
      this.clearMarker();
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        if (pagination && pagination.hasNextPage) {
          this.getNextPage(pagination);
        }
        for (var i = 0; i < results.length; i++) {
          this.placeId.push(results[i].place_id);
          this.locations.push(results[i].geometry.location.toJSON());
          this.marker[i] = new google.maps.Marker({
            // position: results[i].geometry.location.toJSON(),
            position: this.locations[i],
            animation: google.maps.Animation.DROP,
            // icon: markerIcon,
          });
          setTimeout(this.dropMarker(i), i * 100);
          // console.log(results);
          // console.log(this.locations);
          // console.log(this.placeId);
          this.getDetail(results[i].place_id);
        }
        console.log(this.marker.length);
      }
    },

    getNextPage(pagination) {
      pagination.nextPage();
    },

    // 获取详细数据
    getDetail(placeId) {
      // console.log(placeId);
      // for (let i = 0; i < placeId.length; i++) {
      const request = {
        placeId: placeId,
        fields: [
          "name",
          "rating",
          "formatted_phone_number",
          "geometry",
          "international_phone_number",
          "formatted_address",
        ],
      };
      this.details = new google.maps.places.PlacesService(this.map);
      this.details.getDetails(request, this.callbackDetail);
      // }
    },

    callbackDetail(place, status) {
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        // console.log(place);
        // 判断有没有电话号码
        if (place.international_phone_number) {
          this.placeDetail.unshift(place);
          // console.log(this.placeDetail);
        }
        // console.log(place);
        // console.log(this.placeDetail);
      }
    },

    // 添加标记点
    dropMarker(i) {
      setTimeout(() => {
        this.marker[i].setMap(this.map);
      }, i * 100);
    },

    // 清除标记
    clearMarker() {
      for (let i = 0; i < this.marker.length; i++) {
        if (this.marker[i]) {
          this.marker[i].setMap(null);
        }
      }
      this.marker = [];
      this.placeId = [];
      this.locations = [];
      // this.placeDetail = [];
    },

    // 上传采集数据
    uploadDataTxt() {
      this.$message({
        message: "数据上传成功",
        type: "success",
      });
      // var title = ''
      var str = "";
      this.placeDetail.forEach((item) => {
        // 过滤
        let phone = item.international_phone_number
          .replace("-", "")
          .replace("-", "")
          .replace(" ", "");

        // str+='ID:'+item.id+'   '+'名称:'+item.name+'   '+'年龄:'+item.age+'\r\n'
        str += item.name + "," + phone + "\r\n";
        // console.log(str);
      });
      var allStr = str;
      // var allStr = title+'\r\n'+'\r\n'+str
      var export_blob = new Blob([allStr]);
      var save_link = document.createElement("a");
      save_link.href = window.URL.createObjectURL(export_blob);
      save_link.download = "userInfo" + ".txt";
      console.log(save_link);
      this.fakeClick(save_link);
    },

    uploadDataVcf() {
      let str;
      let contact = "";
      this.placeDetail.forEach((item) => {
        // 过滤
        let phone = item.international_phone_number
          .replace("-", "")
          .replace("-", "")
          .replace(" ", "");
        contact +=
          "BEGIN:VCARD" +
          "\n" +
          "VERSION:3.0" +
          "\n" +
          "N:" +
          item.name +
          "\n" +
          "FN:" +
          item.name +
          "\n" +
          "TEL;TYPE=CELL:" +
          phone +
          "\n" +
          "END:VCARD" +
          "\n";
        str = [contact];
        // this.vcord += str + "\r\n"
        this.file = new File(str, {
          type: "text/plain;charset=utf-8",
        });
        // console.log(str);
      });
      saveAs(this.file, "userInfo.vcf");
    },

    fakeClick(obj) {
      var ev = document.createEvent("MouseEvents");
      ev.initMouseEvent(
        "click",
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      );
      obj.dispatchEvent(ev);
    },

    handleSizeChange(val) {
      this.tablePage.pageSize = val;
      console.log(val);
    },

    handleCurrentChange(val) {
      console.log(val);
      this.queryLine.pageNum = val;
    },
  },
};
</script>

<style scoped>
.verticalBar {
  width: 3px;
  height: 18px;
  background: #1074fd;
  display: inline-block;
  vertical-align: top;
  margin-right: 10px;
  margin-top: 2px;
}

.middle_box {
  display: flex;
  justify-content: space-between;
}

.right_box {
  background-color: white;
  padding: 10px;
  height: 900px;
  width: 520px;
}

.right_box_select {
  width: 160px;
}

.bottom_box {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.bottom_box_right {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}

.upload_box {
  display: flex;
  align-items: center;
  background-color: white;
  border: none;
  cursor: pointer;
}

.info_boss {
  padding: 10px;
  margin-top: 10px;
  border-top: 1px solid rgb(230, 226, 226);
  /* border-bottom: 1px solid rgb(230, 226, 226); */
}

.info_box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/deep/ .el-checkbox__label {
  font-size: 20px;
  font-weight: 500;
}

.phone_el {
  font-size: 15px;
  color: #868585;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.address {
  margin-top: 10px;
  font-size: 15px;
  color: #868585;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.detail {
  height: 660px;
  overflow-y: auto;
  overflow-x: hidden;
}

.detail::-webkit-scrollbar {
  display: none;
}

.fenye {
  /* display: unset; */
  margin-top: 10px;
  text-align: center;
}

#search {
  /* width: 80px; */
  /* text-align: center; */
  margin-left: 10px;
}
</style>